package com.yan.service.comonService;

import com.yan.exception.ServiceException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * 邮件服务
 * @author yanchen
 */
@Component
public class MailService {

    /**
     *  JavaMailSender 在Mail自动配置类 MailSenderAutoConfiguration 中已经导入，
     *  这里直接注入使用即可
     */
    @Resource
    JavaMailSender javaMailSender;

    /**
     * 发送带HTML内容的邮件
     * @param from 邮件发送者
     * @param to 收件人
     * @param subject 邮件主题
     * @param content html格式的邮件内容
     */
    public void sendHtmlMail(String from, String to, String subject, String content){
        String system = "<div>信息来自于：小影城网站</div>";
        String htmlContent =  "<!DOCTYPE html> " +  "<html lang='en'> " +
                "<head> " +
                "    <meta charset='UTF-8'> " +
                "    <title>小影城网站</title> " +
                "    <style> " +
                "        .code{ " +
                "            color: #9373EE; " +
                "            font-size: 25px; " +
                "            font-weight: bolder; " +
                "            background-color: #fbfafe; " +
                "            text-align: center; " +
                "        } " +
                "    </style> " +
                "</head> " +
                "<body> " +
                "    <div> 您正在进行&nbsp;&nbsp;" +
                         subject +
                        "，这是您的登录验证码：<span class='code'>" +
                            content +
                        "</span>，验证码3分钟内有效，如非本人操作请勿转给他人，否则将导致账号被盗和个人信息泄漏，谨防诈骗！" +
                "    </div> " +
                     system +
                "</body> " +
                "</html>";
        try {
            MimeMessage message = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setTo(to);
            helper.setFrom(from);
            helper.setSubject(subject);
            helper.setText(htmlContent, true);
            javaMailSender.send(message);

        } catch (MessagingException e) {
            throw new ServiceException("邮件发送失败！");
        }
    }
}
